package br.com.skytef.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadFtp {
	private static final int BUFFER_SIZE = 4096;
	private URLConnection conn;
	
	public DownloadFtp(URLConnection conn){
		this.conn = conn;
	}
	
	public DownloadFtp(){

	}

	

	// Implementacao funcional para testes
	public void download(String nomeArquivo) {
		String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
		String host = "skytefnavs.noip.me";
		String user = "visitante";
		String pass = "skytef";
		String filePath = nomeArquivo;
		String savePath = "C:/Users/denilson dias/Downloads/Teste.zip";

		ftpUrl = String.format(ftpUrl, user, pass, host, filePath);
		System.out.println("URL: " + ftpUrl);

		try {
			URL url = new URL(ftpUrl);
			conn = url.openConnection();
			InputStream inputStream = conn.getInputStream();

			FileOutputStream outputStream = new FileOutputStream(savePath);

			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bytesRead);
			}

			outputStream.close();
			inputStream.close();

			System.out.println("File downloaded");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public InputStream getInputStream(String nomeArquivo) {
		String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
		String host = "skytefnavs.noip.me";
		String user = "visitante";
		String pass = "skytef";
		String filePath = nomeArquivo;

		ftpUrl = String.format(ftpUrl, user, pass, host, filePath);

		try {
			URL url = new URL(ftpUrl);
			conn = url.openConnection();
			InputStream inputStream = conn.getInputStream();
			return inputStream;
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public FileInputStream getFileInputStream(String nomeArquivo) throws URISyntaxException {
		String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
		String host = "skytefnavs.noip.me";
		String user = "visitante";
		String pass = "skytef";
		String filePath = nomeArquivo;

		ftpUrl = String.format(ftpUrl, user, pass, host, filePath);

		try {
			URL url = new URL(ftpUrl);

			File file = new File(url.toURI());
			FileInputStream fileInput = new FileInputStream(file);

			return fileInput;
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public URLConnection getConn() {
		return conn;
	}

	public void setConn(URLConnection conn) {
		this.conn = conn;
	}	
}
